from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import User, db
from utils import error, success
from werkzeug.security import generate_password_hash
from datetime import datetime

user_api = Blueprint('user_api', __name__, url_prefix='/api/users')

@user_api.route('/', methods=['GET'])
@jwt_required()
def get_users():
    """获取用户列表"""
    try:
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        username = request.args.get('username', '')
        role = request.args.get('role', '')
        status = request.args.get('status', '')
        
        query = User.query.filter(User.role == 'operator')  # 只显示操作员
        
        # 搜索过滤
        if username:
            query = query.filter(User.username.contains(username))
        if status:
            query = query.filter(User.status == status)
        
        # 按创建时间倒序排列
        query = query.order_by(User.created_at.desc())
        
        # 分页
        pagination = query.paginate(
            page=page, per_page=page_size, error_out=False
        )
        
        users = []
        for user in pagination.items:
            users.append({
                'id': user.id,
                'username': user.username,
                'role': user.role,
                'name': user.name,
                'gender': user.gender,
                'birth_date': user.birth_date.isoformat() if user.birth_date else None,
                'phone': user.phone,
                'email': user.email,
                'address': user.address,
                'avatar': user.avatar,
                'created_at': user.created_at.isoformat(),
                'updated_at': user.updated_at.isoformat()
            })
        
        return success(data={
            'users': users,
            'pagination': {
                'page': pagination.page,
                'page_size': pagination.per_page,
                'total': pagination.total
            }
        }).to_response()
        
    except Exception as e:
        return error(code=500, msg=f'获取用户列表失败: {str(e)}').to_response()


@user_api.route('/', methods=['POST'])
@jwt_required()
def create_user():
    """创建用户"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 检查当前用户是否为管理员
        current_user = User.query.get(current_user_id)
        if current_user.role != 'admin':
            return error(code=403, msg='权限不足').to_response()
        
        # 验证必填字段
        if not data.get('username'):
            return error(code=400, msg='用户名不能为空').to_response()
        if not data.get('password'):
            return error(code=400, msg='密码不能为空').to_response()
        if not data.get('name'):
            return error(code=400, msg='姓名不能为空').to_response()
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=data['username']).first():
            return error(code=400, msg='用户名已存在').to_response()
        
        # 检查邮箱是否已存在
        if data.get('email') and User.query.filter_by(email=data['email']).first():
            return error(code=400, msg='邮箱已存在').to_response()
        
        # 创建用户（固定为操作员角色）
        user = User(
            username=data['username'],
            role='operator',  # 固定为操作员角色
            name=data['name'],
            gender=data.get('gender'),
            birth_date=datetime.strptime(data['birth_date'], '%Y-%m-%d').date() if data.get('birth_date') and data['birth_date'].strip() else None,
            phone=data.get('phone'),
            email=data.get('email'),
            address=data.get('address')
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.commit()
        
        return success(data={
            'id': user.id,
            'username': user.username,
            'name': user.name,
            'role': user.role
        }, msg='用户创建成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(code=500, msg=f'创建用户失败: {str(e)}').to_response()

@user_api.route('/<int:user_id>', methods=['PUT'])
@jwt_required()
def update_user(user_id):
    """更新用户"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 检查当前用户是否为管理员
        current_user = User.query.get(current_user_id)
        if current_user.role != 'admin':
            return error(code=403, msg='权限不足').to_response()
        
        user = User.query.get_or_404(user_id)
        
        # 更新字段
        if 'username' in data:
            # 检查用户名是否已存在
            if data['username'] != user.username and User.query.filter_by(username=data['username']).first():
                return error(code=400, msg='用户名已存在').to_response()
            user.username = data['username']
        
        if 'role' in data:
            user.role = data['role']
        
        if 'name' in data:
            user.name = data['name']
        
        if 'gender' in data:
            user.gender = data['gender']
        
        if 'birth_date' in data:
            user.birth_date = datetime.strptime(data['birth_date'], '%Y-%m-%d').date() if data['birth_date'] else None
        
        if 'phone' in data:
            user.phone = data['phone']
        
        if 'email' in data:
            # 检查邮箱是否已存在
            if data['email'] and data['email'] != user.email and User.query.filter_by(email=data['email']).first():
                return error(code=400, msg='邮箱已存在').to_response()
            user.email = data['email']
        
        if 'address' in data:
            user.address = data['address']
        
        user.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return success(msg='用户更新成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(code=500, msg=f'更新用户失败: {str(e)}').to_response()

@user_api.route('/<int:user_id>', methods=['DELETE'])
@jwt_required()
def delete_user(user_id):
    """删除用户"""
    try:
        current_user_id = get_jwt_identity()
        
        # 检查当前用户是否为管理员
        current_user = User.query.get(current_user_id)
        if current_user.role != 'admin':
            return error(code=403, msg='权限不足').to_response()
        
        user = User.query.get_or_404(user_id)
        
        # 不能删除管理员
        if user.role == 'admin':
            return error(code=400, msg='不能删除管理员账号').to_response()
        
        # 不能删除自己
        if user.id == current_user_id:
            return error(code=400, msg='不能删除自己的账号').to_response()
        
        db.session.delete(user)
        db.session.commit()
        
        return success(msg='用户删除成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(code=500, msg=f'删除用户失败: {str(e)}').to_response()

@user_api.route('/<int:user_id>/reset-password', methods=['POST'])
@jwt_required()
def reset_password(user_id):
    """重置用户密码"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 检查当前用户是否为管理员
        current_user = User.query.get(current_user_id)
        if current_user.role != 'admin':
            return error(code=403, msg='权限不足').to_response()
        
        user = User.query.get_or_404(user_id)
        
        if 'password' not in data:
            return error(code=400, msg='密码不能为空').to_response()
        
        user.set_password(data['password'])
        user.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return success(msg='密码重置成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(code=500, msg=f'重置密码失败: {str(e)}').to_response()
